package com.nanxhs.proxy.jdk;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Proxy;

/**
 * @author: haibin.tang
 * @date: 2021/2/5
 */
public class Main {

    public static void main(String[] args) {
        UserService userService = (UserService) Proxy.newProxyInstance(UserService.class.getClassLoader(), new Class[]{UserService.class}, new JdkDynamicProxy(new UserServiceImpl()));
        System.out.println(userService.create("小明"));
        System.out.println(userService.create("小红"));
        saveProxyClass2Disk("e://UserService$Proxy.class", new Class[] {UserService.class});
    }

    /**
     * 根据传入的class 生成代理类, 并且把class持久化到磁盘上
     * @param path  持久化路径
     * @param classes  动态生成的代理类需要实现的接口
     */
    public static void saveProxyClass2Disk(String path, Class[] classes){
        byte[] classFile = ProxyGenerator.generateProxyClass(path, classes);
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            fos.write(classFile);
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
